#!/usr/bin/env python
import smtplib
from email.MIMEText import MIMEText
from email.Utils import formatdate
from email.Header import Header
import sys, time

def sendEmailFun(subject, body, type='plain'): 
  # email-info
  smtpPort = '25'
  smtpHost = 'csnet1.cs.tsinghua.edu.cn'
  fromMail = 'argus-alarm@' + smtpHost
  toMail = 'argus@' + smtpHost
  username = fromMail
  password = 'CNPT-argus-cnpt'
  # init
  encoding = 'utf-8'
  mail = MIMEText(body.encode(encoding), type, encoding)
  mail['Subject'] = Header(subject, encoding)
  mail['From'] = '"argus-alarm" <' + fromMail + '>'
  mail['To'] = '"argus" <' + toMail + '>'
  mail['Reply-to'] = '"argus" <' + toMail + '>'
  mail['Date'] = formatdate()
  try:
    ## smtp-server: plain/SSL/TLS
    #smtp = smtplib.SMTP(smtpHost,smtpPort)
    #smtp.ehlo()
    #smtp.login(username,password)
    # tls
    smtp = smtplib.SMTP(smtpHost,smtpPort)
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login(username,password)
    ## ssl
    #sslPort  = '465'
    #smtp = smtplib.SMTP_SSL(smtpHost,sslPort)
    #smtp.ehlo()
    #smtp.login(username,password)
    # send email
    smtp.sendmail(fromMail, toMail, mail.as_string())
    smtp.quit()
    print >> sys.stderr, 'Send email success:', body
  except Exception as e:
    print >> sys.stderr, 'Error: unable to send email:', e 

# alarm_id, time, prefix_dec, homeas, oldhomeas, bad_path
# sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], ...
cmd, alarm_id, timestamp, prefix_dec, new_homeas, old_homeas, bad_path = sys.argv
if new_homeas != "0":
  subject = "%s may be hijacked by suspicious origin AS%s" % (prefix_dec, new_homeas)
  anomaly = "Origin AS changes: from AS%s to AS%s" % (old_homeas, new_homeas)
else:
  as_tuple = bad_path.split()
  if len(as_tuple) == 2:
    bad_path = "AS%s AS%s" % (as_tuple[0], as_tuple[1])
    subject = "%s may be hijacked by suspicious AS neighbour (%s)" % (
        prefix_dec, bad_path)
    anomaly = "Suspicious AS neighbour in path: '%s'" % bad_path
  else: 
    bad_path = "AS%s AS%s AS%s" % (as_tuple[0], as_tuple[1], as_tuple[2])
    subject = "%s may be hijacked by suspicious AS triple (%s)" % (
        prefix_dec, bad_path)
    anomaly = "Suspicious AS triple in path: '%s'" % bad_path
body = (
  """Prefix hijacking alarm:
  Start Time(UTC): %s
  IP Prefix: %s
  %s
  Details: http://argus.csnet1.cs.tsinghua.edu.cn/fingerprints/%s/ """ % (
    time.strftime("%b-%d-%Y %T", time.gmtime(int(timestamp))),
    prefix_dec, anomaly, alarm_id )
)
sendEmailFun(subject, body)

# TODO
# ./sendemail.py 294346 1336395291 213.175.168.0/24 6453 9051 ''
